/*
 * @filename WebUtils.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月9日
 */
package com.bnzj.core.web.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import com.bnzj.core.util.FbConstant;

import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-12-09
 */
@Slf4j
public class WebUtils {
    
    public static Pageable initPage(String pageSizeStr, String pageIndex, Sort sort) {
        if ("undefined".equals(pageSizeStr) || "undefined".equals(pageIndex)) {
            pageSizeStr = null;
            pageIndex = null;
        }
        int current = StringUtils.isEmpty(pageIndex) ? 1 : Integer.parseInt(pageIndex);
        current = current <=1 ? 1 : current;
        int pageSize = StringUtils.isEmpty(pageSizeStr) ? 10 : Integer.parseInt(pageSizeStr);
        //int current = start / pageSize;
        if (sort == null) {
            sort = Sort.unsorted();
        }
        return PageRequest.of(current - 1, pageSize, sort);
    }
    
    /**
     * 编码文件名称
     * @param fileName
     * @return
     */
    public static String encodeFileName(String userAgent, String fileName) {
        String newName = fileName;
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("like Gecko")) {
                newName = URLEncoder.encode(fileName, FbConstant.GLOBAL_ENCODE);
            } else {
                newName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        return newName;
    }
}
